﻿using System.Globalization;
using Microsoft.WindowsAzure.MobileServices;
using System.Windows.Media;
using Newtonsoft.Json.Linq;

namespace SkiTracker.Converter
{
    public class ColorJsonConverter : IDataMemberJsonConverter
    {
        public object ConvertFromJson(JToken value)
        {

            var text = value.ToString();

            if (text.Length == 9)
                return Color.FromArgb(
                    byte.Parse(text.Substring(1, 2), NumberStyles.HexNumber),
                    byte.Parse(text.Substring(3, 2), NumberStyles.HexNumber),
                    byte.Parse(text.Substring(5, 2), NumberStyles.HexNumber),
                    byte.Parse(text.Substring(7, 2), NumberStyles.HexNumber));

            else return App.CurrentApp.AccentColor;
        }

        public JToken ConvertToJson(object instance)
        {
            if (instance is Color)
            {
                var color = (Color)instance;
                return color.ToString();
            }
            else
            {
                return "null";
            }
        }
    }
}
